import React from 'react';
import {
    View,
    Text,
    FlatList,
    TouchableOpacity,
    Dimensions,
    Image,
} from 'react-native';
import styles from './styles';
import NavigationBar from '../../common/NavigationBar';
import {BASE_URL} from '../../common/BASE_URL';
import HttpUtils from '../../expand/dao/HttpUtils';
import {Constant, StylesConstant} from '../../common/Constant';
import StorageUtil from '../../utils/StorageUtil';
import NavigationUtil from '../../navigators/NavigationUtil';
import Utils from '../../utils/Utils';
import GlobalStyles from '../../common/styles/GlobalStyles';
import {Tabs} from '@ant-design/react-native';
import ToastUtil from '../../utils/ToastUtil';
import CaseItem from './components/CaseItem';
import AcceptItem from './components/AcceptItem';

let current = 0;
let total = 0;
const size = 10;
// 巡查列表
const getInspectionRecordsUrl = BASE_URL.apiBaseUrl + '/app/inspectionRecords/simple'
// 案件列表
const getCaseInfoUrl = BASE_URL.apiBaseUrl + '/app/viewCaseInfo/simple'
// 事件列表
const getAcceptCaseUrl = BASE_URL.apiBaseUrl + '/app/viewAcceptCases/simple'

export default class DeptList extends React.Component {
    constructor(props) {
        super(props);
        // 获取参数
        let tabIndex = 0;
        this.state = {
            tabIndex: tabIndex,
            isLoading: false, // list加载状态
            hideLoadingMore: false,
            caseList: [],
            dataList2: [],
            query: {
                // current: 1, // 当前页数
                // size: 10, // 每页大小
                queryStr: '', // 模糊查询
            },
        };
    }

    componentDidMount() {
        this.loadData();
    }

    loadData(loadMore) {
        const {tabIndex} = this.state;
        if(this.state.isLoading) return
        let url = ''
        let params = {size: size, page: current, sort: 'caseTime,desc'}
        if(tabIndex === 0) {
            url = getCaseInfoUrl
        }else if(tabIndex === 1) {
            url = getAcceptCaseUrl
        }else if(tabIndex === 2) {
            url = getInspectionRecordsUrl
        }
        if(url) {
            // this.state.isLoading = true
            const bool = this.isLoadMore(loadMore); // 4.的判断是否需要加载更多
            if(bool){
                HttpUtils.request({
                    url: url,
                    params
                }).then(res=>{
                    const {content, totalElements} = res
                    const data = {
                        caseList: loadMore
                            ? this.state.dealtCaseList.concat(content)
                            : content,
                    }
                    const totalPage = parseInt(((totalElements-1)/size))
                    total = totalPage;
                    if (current == totalPage) {
                        data.hideLoadingMore = true;
                    }
                    // 如果当前查询的是第一页，但是没有查出数据，给出提示，并修改底部文字
                    if (current == 0 && content.length === 0) {
                        data.hideLoadingMore = true;
                        ToastUtil.info('没找到相关数据');
                    }
                    this.setState({
                        isLoading: false,
                        ...data
                    })
                }).catch(e=>{
                    this.setState({
                        isLoading: false
                    })
                })
            }
        }
    }
    // 初始化数据
    async initDriverList() {
        const code = await StorageUtil.get(Constant.companyCode);
        if (code) {
            this.setState({
                isLoading: true,
            });
            HttpUtils.request({
                // url: URL,
                type: 'post',
                data: {companyCode: code, type: this.state.type},
            })
                .then((result) => {
                    const data = result.data;
                    this.setState({
                        caseList: data,
                        isLoading: false,
                    });
                })
                .catch((_) => {
                    this.setState({
                        isLoading: false,
                    });
                });
        }
    }

    render() {
        const {navigation} = this.props;
        const {tabIndex} = this.state;
        return (
            <View style={GlobalStyles.pageContainer}>
                {/* 自定义顶部导航条 */}
                <NavigationBar navigation={navigation} headerBackTitle={'部门列表'} />
                    <View style={{flex: 1}}>
                        <Tabs
                            style={[styles.container, GlobalStyles.bgGrey]}
                            initialPage={tabIndex}
                            tabBarTextStyle={GlobalStyles.tabsTextStyle}
                            tabBarUnderlineStyle={GlobalStyles.tabsLineStyle}
                            tabBarActiveTextColor={GlobalStyles.tabBarActiveTextColor}
                            tabBarInactiveTextColor={GlobalStyles.tabBarInactiveTextColor}
                            onChange={(tab, index) => this.handleTabChange(tab, index)}
                            tabs={[
                                {title: '案件列表'},
                                {title: '事件列表'},
                                {title: '巡查列表'},
                            ]}>
                            <View tabLabel="案件列表">{this._renderCaseList()}</View>
                            <View tabLabel="事件列表">{this._renderAcceptList()}</View>
                            <View tabLabel="巡查列表">{this._renderCaseList()}</View>
                        </Tabs>
                    </View>
            </View>
        );
    }

    _renderCaseList(){
        const {caseList, isLoading} = this.state;
        return (
            <FlatList
                style={styles.list}
                data={caseList}
                keyExtractor={(item, index) => `case_${index}`}
                renderItem={(data) => this._renderCaseItem(data)}
                refreshControl={Utils.renderRefreshControl('加载中', isLoading, () => {
                    this.loadData();
                })}
                ListFooterComponent={() => this.genIndicator()}
                onEndReached={() => {
                    setTimeout(() => {
                        if (this.canLoadMore) {
                            this.loadData(true);
                            this.canLoadMore = false;
                        }
                    }, 100);
                }}
                onEndReachedThreshold={0.5}
                onMomentumScrollBegin={() => {
                    this.canLoadMore = true;
                }}
            />
        );
    }
    _renderAcceptList(){
        const {caseList, isLoading, tabIndex} = this.state;
        return (
            <FlatList
                style={styles.list}
                data={caseList}
                keyExtractor={(item, index) => item.caseCode}
                renderItem={(data) => this._renderAcceptItem(data)}
                refreshControl={Utils.renderRefreshControl('加载中', isLoading, () => {
                    this.loadData();
                })}
                ListFooterComponent={() => this.genIndicator()}
                onEndReached={() => {
                    setTimeout(() => {
                        if (this.canLoadMore) {
                            this.loadData(true);
                            this.canLoadMore = false;
                        }
                    }, 100);
                }}
                onEndReachedThreshold={0.5}
                onMomentumScrollBegin={() => {
                    this.canLoadMore = true;
                }}
            />
        );
    }

    handleTabChange(obj, index) {

        if (this.state.tabIndex !== index) {
            this.state.tabIndex = index;
            this.state.caseList = []
            this.loadData();
        }
    }
    _renderCaseItem(data){
        const {item} = data;
        const {tabIndex} = this.state
        return (
            <CaseItem
                item={item}
                handleCallback={() => {
                    if(tabIndex === 0){
                        NavigationUtil.goPage('CaseReport', {
                            caseCode: item.caseCode,
                            matterId: item.id,
                            linkId:item.linkId,
                            type: 'caseInfo',
                            submitType: 'detail'
                        });
                    }else if(tabIndex === 2) {
                        NavigationUtil.goPage('CaseReport', {
                            caseCode: item.caseCode,
                            matterId: item.id,
                            linkId:item.linkId,
                            type: 'inspection',
                            submitType: 'detail'
                        });
                    }
                }}
            />
        );
    }
    _renderAcceptItem(data){
        const {item} = data;
        return (
            <AcceptItem
                item={item}
                handleCallback={() => {
                    NavigationUtil.goPage('CaseReport', {
                        caseCode: item.caseCode,
                        matterId: item.id,
                        linkId: item.linkId,
                        type: 'clue',
                        submitType: 'detail'
                    })
                }}
            />
        );
    }

    isLoadMore(loadMore) {
        // 如果触发了加载更多，但是当前页数 === 总页数，做出提示，终止该函数运行
        if (loadMore && current == total) {
            ToastUtil.info('没有更多了'); // 弹框提示
            this.setState({
                hideLoadingMore: true,
            });
            return false;
        }
        if (loadMore) {
            current++;
        } else {
            current = 0;
            this.setState({
                hideLoadingMore: false,
            });
        }
        return true;
    }

    genIndicator() {
        const {hideLoadingMore} = this.state;
        return hideLoadingMore
            ? Utils.renderNoDataBottom()
            : Utils.renderLoadingMore();
    }

    getListBottom(isLoading, data) {
        return !isLoading && data && data.length === 0
            ? Utils.renderNoDataBottom()
            : null;
    }

}
